package com.google.code.gwt.storage.client;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.logging.Logger;

public class Storage {

	private static final Logger log = Logger.getLogger("Storage Mock");
	HashMap<String, String> map = new HashMap<String, String>();

	ArrayList<String> keys = new ArrayList<String>();

	public static boolean isSupported() {
		return true;
	}

	public static Storage getLocalStorage() {
		log.info("Mocking local storage");
		return new Storage();
	};

	public static Storage getSessionStorage() {
		log.info("Mocking session storage");
		return new Storage();
	}

	public static void addStorageEventHandler(StorageEventHandler handler) {
	}

	public static void removeStorageEventHandler(StorageEventHandler handler) {

	}

	public int getLength() {
		return map.size();
	}

	public String key(int index) {
		return keys.get(index);
	}

	/**
	 * Returns the item in the Storage associated with the specified key.
	 * 
	 * @param key
	 *            the key to a value in the Storage
	 * @return the value associated with the given key
	 * @see <a href="http://www.w3.org/TR/webstorage/#dom-storage-getitem">W3C
	 *      Web Storage - Storage.getItem(k)</a>
	 */
	public String getItem(String key) {
		return map.get(key);
	}

	/**
	 * Sets the value in the Storage associated with the specified key to the
	 * specified data.
	 * 
	 * @param key
	 *            the key to a value in the Storage
	 * @param data
	 *            the value associated with the key
	 * @see <a href="http://www.w3.org/TR/webstorage/#dom-storage-setitem">W3C
	 *      Web Storage - Storage.setItem(k,v)</a>
	 */
	public void setItem(String key, String data) {
		map.put(key, data);
		int index = keys.indexOf(key);
		if (index == -1)
			keys.add(key);
		else
			keys.set(index, key);
	}

	/**
	 * Removes the item in the Storage associated with the specified key.
	 * 
	 * @param key
	 *            the key to a value in the Storage
	 * @see <a
	 *      href="http://www.w3.org/TR/webstorage/#dom-storage-removeitem">W3C
	 *      Web Storage - Storage.removeItem(k)</a>
	 */
	public void removeItem(String key) {
		map.remove(key);
		keys.remove(key);
	};

	/**
	 * Removes all items in the Storage.
	 * 
	 * @see <a href="http://www.w3.org/TR/webstorage/#dom-storage-clear">W3C Web
	 *      Storage - Storage.clear()</a>
	 */
	public void clear() {
		map.clear();
		keys.clear();
	}
}
